const { spawn } = require('child_process')
const fs = require('fs').promises
const path = require('path')
const dotenv = require('dotenv')

// eslint-disable-next-line no-undef
const dirname = __dirname

// 根据环境变量选择不同的 .env 文件
const envFile = process.env.NODE_ENV === 'prod' ? '.env.prod' : '.env.dev'
// 加载环境变量
dotenv.config({ path: path.resolve(dirname, '../../', envFile) })

const VITE_APPID = process.env.VITE_APPID
const VITE_PROJECT_NAME = process.env.VITE_PROJECT_NAME
console.log('[ process.env ] >', process.env)
// 动态设置 manifest.json 路径
const manifestPath = path.join(dirname, '../manifest.json')

async function updateManifest(environment) {
  try {
    // 读取 manifest.json
    const fileData = await fs.readFile(manifestPath, 'utf8')
    const manifest = JSON.parse(fileData)

    // 更新 appid
    manifest['mp-weixin'].appid = VITE_APPID || manifest['mp-weixin'].appid
    manifest['mp-weixin'].setting = manifest['mp-weixin'].setting || {}
    manifest['mp-weixin'].projectname = VITE_PROJECT_NAME || manifest['mp-weixin'].projectname || ''

    // 写回 manifest.json
    await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf8')
  } catch (error) {
    console.error(`更新 manifest.json (${environment}) 失败:`, error)
    process.exit(1)
  }
}

async function deleteDist(environment, isBuild) {
  const distPath =
    environment === 'dev'
      ? path.join(dirname, `../../dist/dev`)
      : isBuild
        ? path.join(dirname, `../../dist/prod`)
        : path.join(dirname, `../../dist/${environment}`)
  try {
    await fs.rm(distPath, { recursive: true, force: true })
  } catch (error) {
    if (error.code !== 'ENOENT') {
      console.error(`删除 dist 目录失败:`, error)
    }
  }
}

// 运行打包或开发命令
function runUniApp(environment, isBuild) {
  const uniCommand = isBuild ? 'build' : 'dev'
  const uniProcess = spawn('uni', [uniCommand, '-p', 'mp-weixin', '--mode', environment], {
    shell: true
  })

  uniProcess.stdout.on('data', data => console.log(data.toString()))
  uniProcess.stderr.on('data', data => console.error(data.toString()))
  uniProcess.on('close', code => console.log(`子进程退出，退出码 ${code}`))
}

// 主函数，执行打包或开发流程
async function main() {
  const environment = process.env.NODE_ENV === 'prod' ? 'prod' : 'dev'
  const isBuild = process.env.BUILD === 'true'
  console.log('[ isBuild ] >', isBuild)
  try {
    // 删除指定环境的目录
    await deleteDist(environment, isBuild)

    // 更新 manifest.json 并运行打包或开发命令
    await updateManifest(environment)
    runUniApp(environment, isBuild)
  } catch (error) {
    console.error('启动过程中发生错误:', error)
    process.exit(1)
  }
}

// 运行主程序
main()
